import React, { useState, useEffect } from 'react';
import styles from './index.module.css';
import {
  Form,
  Button,
  Badge,
  Input,
  Select,
  DatePicker,
  Table,
  Pagination,
  TreeSelect,
  Modal,
  message,
  Drawer,
  Tabs,
} from 'antd';
import type { TableColumnsType, TabsProps, TableProps } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import axios from 'axios';
import moment from 'moment';

// 全局数据data的类型声明
interface dataItem {
  status: number;
  layout: number;
  id: string;
  name: string;
  account: any;
  title: string;
  gradeid: number;
  certid: number;
}
// 全局数据pageData的类型声明
interface pageDataItem {
  status: number;
  layout: number;
  id: string;
  name: string;
  account: any;
  title: string;
  gradeid: number;
  certid: number;
}

// 添加的表单声明
interface AppendForm {
  name: string;
  tel: string;
  idcard: any;
  sex: any;
  birthday: any;
  address: any;
  record: any;
  projectid: number;
  companyid: number;
  bank_card: string;
  bank: string;
  agreement_end: any;
  agreement_num: any;
  base_pay: string;
  gradeid: any;
  political_status: any;
  layout: number;
  status: number;
  leave_time: any;
  entry_time: any;
  gr_security: string;
  dw_security: string;
}

// 添加的表单验证
const AddRules = {
  name: [
    { required: true, message: '请输入员工姓名' },
    { max: 20, message: '姓名不能超过20个字符' },
  ],
  tel: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
  ],
  idcard: [
    { required: true, message: '请输入证件号' },
    { pattern: /^\d{17}[\dXx]$/, message: '证件号格式不正确' },
  ],
  address: [{ required: true, message: '请输入籍贯' }],
  gradeid: [{ required: true, message: '请选择档级' }],
  record: [{ required: true, message: '请选择学历' }],
  bank: [{ required: true, message: '请输入开户行' }],
  bank_card: [{ required: true, message: '请输入银行卡号' }],
  political_status: [{ required: true, message: '请选择政治面貌' }],
  companyid: [{ required: true, message: '请选择公司' }],
  projectid: [{ required: true, message: '请输入项目' }],
  layout: [{ required: true, message: '请选择用工形式' }],
  status: [{ required: true, message: '请选择员工状态' }],
  agreement_end: [{ required: true, message: '请选择合同到期时间' }],
  agreement_num: [{ required: true, message: '请输入现合同期限' }],
  entry_time: [{ required: true, message: '请选择入职时间' }],
};

// 全选的数据类型声明
interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}

// 档级的数据声明
interface gradeItem {
  id: number;
  name: string;
  money: string;
}

// 项目的数据声明
interface projectItem {
  id: number;
  title: string;
}

// 抽屉的表单
interface drawerForm {
  name: string;
  tel: string;
  idcard: any;
  sex: any;
  birthday: any;
  address: any;
  record: any;
  projectid: number;
  companyid: number;
  bank_card: string;
  bank: string;
  agreement_end: any;
  agreement_num: any;
  base_pay: string;
  gradeid: any;
  political_status: any;
  layout: number;
  status: number;
  leave_time: any;
  entry_time: any;
  create_time: any;
  contract_between: any;
  password: string;
  gr_security: string;
  dw_security: string;
}

interface DataTransfer {
  id: string | number;
}
export default function index() {
  // 声明全局数据用于渲染
  const [data, setdata] = useState<dataItem[]>([]);
  // 声明分页数据用于渲染分页以及搜索
  const [pageData, setpageData] = useState<pageDataItem[]>([]);
  // 公司数据声明
  const [companylist, setcompanylist] = useState([
    { id: 0, account: '', companylist: [], project: [] },
  ]);
  const [company, setcompany] = useState([{ id: 0, account: '', companylist: [] }]);
  // 档级数据声明
  const [graderender, setgraderender] = useState<gradeItem[]>([]);
  const [graed, setgraed] = useState<gradeItem[]>([]);
  // 证书数据声明
  const [cert, setcert] = useState([{ id: 1, title: '' }]);
  // 重复人员声明
  const [repeat, setrepeat] = useState([{ status: 0, layout: 0, name: '' }]);
  // 项目数据的声明获取
  const [project, setproject] = useState<projectItem[]>([]);
  // 添加弹窗的状态
  const [open, setOpen] = useState(false);
  // 抽屉弹窗的状态
  const [DrawerState, setDrawerState] = useState(false);
  // 编辑弹窗的状态
  const [EditOpen, setEditOpen] = useState(false);
  // 删除弹窗的状态
  const [deleteOpen, setdeleteOpen] = useState(false);
  useEffect(() => {
    // 员工接口请求
    const staffData = async () => {
      try {
        const response = await axios.post('/user/index/index');
        setdata(response.data.data);
        setpageData(response.data.data);
        let duplicates = [];
        for (let i in response.data.data) {
          for (let s in response.data.data) {
            if (response.data.data[i].name === response.data.data[s].name && i !== s) {
              duplicates.push(response.data.data[s]);
            }
          }
        }
        setrepeat(duplicates);
        console.log(response.data.data);
      } catch (err) {
        console.error('请求失败:', err);
      }
    };
    // 公司接口请求
    const companyData = async () => {
      try {
        const response = await axios.post('/organization/index/index');
        setcompany(response.data.companylist);
        setcompanylist(response.data.data);
      } catch (err) {
        console.error('请求失败:', err);
      }
    };
    // 档级的数据请求
    const gradeData = async () => {
      try {
        const response = await axios.post('/grade/index/index');
        setgraderender(response.data.list);
        setgraed(buildTreeEnhanced(response.data.list));
      } catch (err) {
        console.error('请求失败:', err);
      }
    };
    // 证书的数据请求
    const certData = async () => {
      try {
        const response = await axios.post('/user/certclass/index');
        setcert(response.data.data);
      } catch (err) {
        console.error('请求失败:', err);
      }
    };

    certData();
    gradeData();
    staffData();
    companyData();
  }, []);

  // 构建二级树结构
  const buildTreeEnhanced = (
    data: Array<{ id: number; pid: number; title: string }>,
    handleOrphans: boolean = false,
  ): any => {
    if (!Array.isArray(data) || data.length === 0) {
      return []; // 如果数据为空，直接返回空数组
    }
    const nodeMap: { [key: number]: any } = {};
    const tree: any[] = [];
    const orphanNodes: any[] = [];
    // 单次遍历构建树结构
    data.forEach((item) => {
      // 初始化节点
      if (!nodeMap[item.id]) {
        nodeMap[item.id] = {
          value: item.id, // 必须字段
          label: item.title, // 必须字段
          ...item, // 保留原始数据
          children: [], // 初始化子节点
        };
      }
      const parentNode = nodeMap[item.pid];
      if (item.pid === 0) {
        tree.push(nodeMap[item.id]); // 根节点
      } else if (parentNode) {
        parentNode.children.push(nodeMap[item.id]); // 子节点
      } else {
        orphanNodes.push(nodeMap[item.id]); // 孤儿节点
      }
    });
    return tree;
  };

  // 分页的数据渲染
  const columns: TableColumnsType<Array<DataTransfer>> = [
    {
      title: '名称',
      width: 100,
      key: 'id',
      fixed: 'left',
      align: 'center',
      render: (record) => (
        <p
          style={{ cursor: 'pointer', color: 'rgb(33, 81, 197)' }}
          onClick={() => showDrawer(record)}
        >
          {record.name}
        </p>
      ),
    },
    {
      title: '岗位工资',
      width: 120,
      dataIndex: 'base_pay',
      key: 'id',
      fixed: 'left',
      align: 'center',
    },
    {
      title: '档级岗位',
      width: 120,
      dataIndex: 'grade_title',
      key: 'id',
      fixed: 'left',
      align: 'center',
    },
    { title: '性别', dataIndex: 'sex', key: 'id', align: 'center', width: 100 },
    { title: '生日', dataIndex: 'birthday', key: 'id', align: 'center' },
    { title: '手机号', dataIndex: 'tel', key: 'id', align: 'center', width: 100 },
    { title: '身份证号', dataIndex: 'idcard', key: 'id', align: 'center', width: 100 },
    { title: '项目名称', dataIndex: 'title', key: 'id', align: 'center', width: 150 },
    { title: '公司名称', dataIndex: 'account', key: 'id', align: 'center', width: 100 },
    { title: '政治面貌', dataIndex: 'political_status', key: 'id', align: 'center', width: 100 },
    { title: '籍贯', dataIndex: 'address', key: 'id', align: 'center', width: 100 },
    { title: '学历', dataIndex: 'record', key: 'id', align: 'center', width: 150 },
    { title: '创建时间', dataIndex: 'create_time', key: 'id', align: 'center', width: 130 },
    { title: '员工状态', dataIndex: 'status', key: 'id', align: 'center', width: 100 },
    { title: '用工形式', dataIndex: 'layout', key: 'id', align: 'center', width: 100 },
    { title: '入职时间', dataIndex: 'start_time', key: 'id', align: 'center', width: 100 },
    { title: '合同时间区间', dataIndex: 'agreement_num', key: 'id', align: 'center', width: 130 },
    { title: '离职时间', dataIndex: 'end_time', key: 'id', align: 'center', width: 100 },
    { title: '现合同期限', dataIndex: 'agreement_num', key: 'id', align: 'center', width: 130 },
    { title: '银行卡卡号', dataIndex: 'bank_card', key: 'id', align: 'center', width: 100 },
    { title: '工资卡开户行', dataIndex: 'bank', key: 'id', align: 'center', width: 300 },
    {
      title: '操作',
      key: 'id',
      fixed: 'right',
      width: 100,
      align: 'center',
      render: () => <p>操作</p>,
    },
  ];

  // 声明当前页
  const [currentPage, setCurrentPage] = useState(1);
  // 声明当前页数量
  const [pageSize, setPageSize] = useState(10);
  // 计算分页后的数据
  const paginatedData = pageData.slice((currentPage - 1) * pageSize, currentPage * pageSize);
  // 处理分页变化
  const handlePageChange = (page: any, size: any) => {
    setCurrentPage(page);
    setPageSize(size);
  };
  // 点击过滤函数
  const screening = (filterData: any) => {
    setpageData(filterData);
    if (filterData.length == data.length) {
      form.resetFields();
    }
  };
  // 搜索表单
  type FieldType = {
    name?: string;
    company?: number;
    itemName?: string;
    grade?: number;
    cert?: number;
    month?: string;
  };
  // 搜索表单
  const [form] = Form.useForm<FieldType>();
  // 搜索函数
  const searchData = (values: FieldType) => {
    const search = form.getFieldsValue();
    if (
      !search.name &&
      !search.company &&
      !search.itemName &&
      !search.grade &&
      !search.cert &&
      !search.month
    ) {
      return setpageData(data);
    }
    const filteredData = () => {
      return pageData.filter((item) => {
        // 检查每个字段是否满足相应条件（如果该搜索条件存在）
        const nameMatch =
          !search.name ||
          (item.name && item.name.toString().toLowerCase().includes(search.name.toLowerCase()));
        const company = !search.company || item.account == search.company;
        const itemNameMatch =
          !search.itemName ||
          (item.title &&
            item.title.toString().toLowerCase().includes(search.itemName.toLowerCase()));

        const gradeMatch =
          !search.grade || (item.gradeid && item.gradeid.toString() === search.grade.toString());

        // 证书条件匹配
        const certMatch =
          !search.cert ||
          (item.certid && item.certid.some((subItem: any) => subItem.certclassid === search.cert));

        return nameMatch && company && itemNameMatch && gradeMatch && certMatch;
      });
    };
    setpageData(filteredData);
  };

  // 弹窗显示事件
  const showModal = () => {
    setOpen(true);
  };
  // 编辑弹窗显示回显事件
  const EditModal = async () => {
    setOpen(true);
    setEditOpen(true);
    // 1. 先加载项目数据
    for (let i in companylist) {
      if (editItem.companyid == companylist[i].id) {
        await setproject(companylist[i].project); // 等待项目数据更新
        break;
      }
    }
    append.setFieldsValue({
      name: editItem.name,
      tel: editItem.tel,
      sex: editItem.sex,
      birthday: editItem.birthday,
      address: editItem.address,
      record: editItem.record,
      projectid: editItem.projectid,
      political_status: editItem.political_status,
      idcard: editItem.idcard,
      bank_card: editItem.bank_card,
      bank: editItem.bank,
      status: editItem.status,
      layout: editItem.layout,
      entry_time: editItem.entry_time ? moment(editItem.entry_time) : null,
      leave_time: editItem.leave_time ? moment(editItem.leave_time) : null,
      agreement_end: editItem.agreement_end ? moment(editItem.agreement_end) : null,
      agreement_num: editItem.agreement_num,
      base_pay: editItem.base_pay,
      companyid: editItem.companyid,
      gr_security: editItem.gr_security,
      dw_security: editItem.dw_security,
      gradeid: editItem.gradeid,
    });
  };
  // 弹窗隐藏事件
  const hideModal = () => {
    setOpen(false);
    setEditOpen(false);
    append.resetFields();
  };

  // 弹窗确认事件
  const affirm = async () => {
    if (!EditOpen) {
      // 添加员工
      try {
        const appendfromValue = append.getFieldsValue();
        console.log(appendfromValue);
        await append.validateFields();
        appendfromValue.entry_time = new Date().toLocaleDateString();
        appendfromValue.agreement_end = new Date().toLocaleDateString();
        appendfromValue.leave_time = new Date().toLocaleDateString();
        const response = await axios.post('/user/index/add', appendfromValue);
        console.log(response.data);
        if (response.data.code == 1) {
          message.success('添加成功');
          setOpen(false);
          append.resetFields();
        }
      } catch (err) {
        console.error('请求失败:', err);
      }
    } else {
      // 编辑员工
      try {
        const appendfromValue = append.getFieldsValue();
        appendfromValue.entry_time = new Date().toLocaleDateString();
        appendfromValue.leave_time = new Date().toLocaleDateString();
        appendfromValue.agreement_end = new Date().toLocaleDateString();
        const editfromValue = {
          id: editItem.id,
          idcard: appendfromValue.idcard,
          birthday: appendfromValue.birthday,
          address: appendfromValue.address,
          record: appendfromValue.record,
          bank_card: appendfromValue.bank_card,
          bank: appendfromValue.bank,
          agreement_end: appendfromValue.agreement_end,
          agreement_num: appendfromValue.agreement_num,
          political_status: appendfromValue.political_status,
          layout: appendfromValue.layout,
          status: appendfromValue.status,
          dw_security: appendfromValue.dw_security,
          gr_security: appendfromValue.gr_security,
          entry_time: appendfromValue.entry_time,
          leave_time: appendfromValue.leave_time,
        };
        console.log(editfromValue, '编辑接口数据');
        console.log(editItem, '当前数据');
        console.log(appendfromValue, '表单数据');
        await append.validateFields();
        const response = await axios.post('/user/index/edit', editfromValue);
        console.log(response.data);
        if (response.data.code == 1) {
          message.success('修改成功');
          setOpen(false);
          append.resetFields();
        }
      } catch (err) {
        console.error('请求失败:', err);
      }
    }
  };
  // 生日和性别的渲染
  const birthdayRender = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 获取输入值（自动去除空格）
    const idCard = e.target.value.trim();
    if (idCard && /^\d{17}[\dXx]$/.test(idCard)) {
      const genderDigit = parseInt(idCard.charAt(16));
      const birthStr = idCard.substring(6, 14);
      append.setFieldsValue({
        sex: genderDigit % 2 === 1 ? '男' : '女',
        birthday: `${birthStr.substring(0, 4)}-${birthStr.substring(4, 6)}-${birthStr.substring(6, 8)}`,
      });
    } else {
      // 清除已填充的值
      append.setFieldsValue({
        birthday: undefined,
        sex: undefined,
      });
    }
  };
  // 当即工资的渲染事件
  const laborage = (e: any) => {
    const Grade = e;
    if (e) {
      for (let i = 0; i < graderender.length; i++) {
        if (graderender[i].id == Grade) {
          console.log(graderender[i]);
          append.setFieldsValue({
            base_pay: graderender[i].money,
          });
        }
      }
    } else {
      append.setFieldsValue({
        base_pay: '',
      });
    }
  };

  // 项目列表下拉框渲染函数
  const projectRender = (e: any) => {
    console.log(e);
    for (let i in companylist) {
      if (companylist[i].id == e) {
        console.log(companylist[i]);
        setproject(companylist[i].project);
      }
    }
  };
  const [append] = Form.useForm<AppendForm>();
  const [editItem, setEditItem] = useState<any>({});
  // 抽屉显示回显事件
  const showDrawer = (item: any) => {
    setEditItem(item);
    setDrawerState(true);
    drawerform.setFieldsValue({
      name: item.name,
      sex: item.sex,
      address: item.address,
      birthday: item.birthday,
      idcard: item.idcard,
      tel: item.tel,
      bank: item.bank,
      bank_card: item.bank_card,
      political_status: item.political_status,
      base_pay: item.base_pay,
      layout: item.layout,
      projectid: item.title,
      companyid: item.account,
      create_time: item.create_time,
      entry_time: item.entry_time,
      agreement_end: item.agreement_end,
      leave_time: item.leave_time,
      gradeid: item.gradeid,
      status: item.status,
      gr_security: item.gr_security,
      dw_security: item.dw_security,
    });
  };
  // 抽屉关闭事件
  const onClose = () => {
    setDrawerState(false);
    setEditItem({});
  };
  // 抽屉的表单声明
  const [drawerform] = Form.useForm<drawerForm>();
  // 选项卡的显示
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: '基本信息',
      children: (
        <>
          <div className={styles.drawerTop}>
            <p className={styles.drawerTopTitle}>岗位信息</p>
            <p className={styles.drawerTopBut} onClick={EditModal}>
              编辑
            </p>
          </div>
          <Form form={drawerform} className={styles.addFormStyle}>
            <Form.Item<drawerForm>
              name="name"
              layout="vertical"
              label="姓名"
              className={styles.addItem}
            >
              <Input placeholder="请输入员工姓名" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="sex"
              layout="vertical"
              label="性别"
              className={styles.addItem}
            >
              <Input placeholder="请输入员工性别" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="address"
              layout="vertical"
              label="籍贯"
              className={styles.addItem}
            >
              <Input placeholder="请输入员工籍贯" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="record"
              layout="vertical"
              label="学历"
              className={styles.addItem}
            >
              <Input placeholder="请输入员工学历" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="tel"
              layout="vertical"
              label="电话"
              className={styles.addItem}
            >
              <Input placeholder="请输入手机号" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="political_status"
              layout="vertical"
              label="形象"
              className={styles.addItem}
            >
              <Input placeholder="请输入形象" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="idcard"
              layout="vertical"
              label="证件号"
              className={styles.addItem}
            >
              <Input placeholder="请输入证件号" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="bank_card"
              layout="vertical"
              label="银行卡号"
              className={styles.addItem}
            >
              <Input placeholder="请输入银行卡" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="companyid"
              layout="vertical"
              label="公司"
              className={styles.addItem}
            >
              <Input placeholder="请输入所在公司" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="layout"
              layout="vertical"
              label="用工形式"
              className={styles.addItem}
            >
              <Input placeholder="请输入用工形式" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="gradeid"
              layout="vertical"
              label="岗位档级"
              className={styles.addItem}
            >
              <Input placeholder="请输入岗位档级" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="base_pay"
              layout="vertical"
              label="岗位工资"
              className={styles.addItem}
            >
              <Input placeholder="输入岗位工资" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="create_time"
              layout="vertical"
              label="创建时间"
              className={styles.addItem}
            >
              <Input placeholder="输入创建时间" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="projectid"
              layout="vertical"
              label="项目"
              className={styles.addItem}
            >
              <Input placeholder="输入所属项目" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="bank"
              layout="vertical"
              label="开户行"
              className={styles.addItem}
            >
              <Input placeholder="请输入开户行" disabled />
            </Form.Item>

            <Form.Item<drawerForm>
              name="agreement_end"
              layout="vertical"
              label="合同到期时间"
              className={styles.addItem}
            >
              <Input placeholder="输入到期时间" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="contract_between"
              layout="vertical"
              label="签订年数"
              className={styles.addItem}
            >
              <Input placeholder="请输入签订年数" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="password"
              layout="vertical"
              label="密码"
              className={styles.addItem}
            >
              <Input placeholder="请输入密码" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="gr_security"
              layout="vertical"
              label="个人社保基数"
              className={styles.addItem}
            >
              <Input placeholder="请输入个人社保基数" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="dw_security"
              layout="vertical"
              label="单位社保基数"
              className={styles.addItem}
            >
              <Input placeholder="请输入单位社保基数" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="entry_time"
              layout="vertical"
              label="入职时间"
              className={styles.addItem}
            >
              <Input placeholder="请输入入职时间" disabled />
            </Form.Item>
            <Form.Item<drawerForm>
              name="leave_time"
              layout="vertical"
              label="离职时间"
              className={styles.addItem}
            >
              <Input placeholder="请输入离职时间" disabled />
            </Form.Item>
          </Form>
        </>
      ),
    },
    {
      key: '2',
      label: '员工合同',
      children: '',
    },
    {
      key: '3',
      label: '工资社保',
      children: '',
    },
    {
      key: '4',
      label: '证书列表',
      children: '',
    },
  ];

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const rowSelection: TableProps<DataTransfer>['rowSelection'] = {
    type: 'checkbox',
    selectedRowKeys, // 绑定选中状态
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys); // 更新选中状态
    },
  };
  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
  // 删除弹窗显示
  const showdelete = () => {
    if (selectedRowKeys.length == 0) {
      message.warning('请选择要删除的数据');
    } else {
      setdeleteOpen(true);
    }
  };
  // 删除弹窗隐藏
  const hidedelete = () => {
    setdeleteOpen(false);
  };

  const deleteData = async () => {
    try {
      const response = await axios.post('/user/index/del', {id:selectedRowKeys.join(',')});
      console.log(response.data);
      if (response.data.code == 1) {
        message.success('删除成功');
        setdeleteOpen(false);
        append.resetFields();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  return (
    <div>
      <p className={styles.title}>员工管理</p>
      {/* 顶部的筛选按钮 */}
      <div className={styles.top_but_box}>
        <div className={styles.top_filter_box}>
          <Badge
            color="#F56C6C"
            count={data.filter((item) => item.status == 1).length}
            overflowCount={999}
          >
            <Button onClick={() => screening(data.filter((item) => item.status === 1))}>
              入职
            </Button>
          </Badge>
          <Badge
            color="#F56C6C"
            count={data.filter((item) => item.status === 2).length}
            overflowCount={999}
          >
            <Button
              onClick={() => screening(data.filter((item) => item.status === 2))}
              style={{ backgroundColor: '#F56C6C', color: 'white' }}
              color="red"
              variant="solid"
            >
              离职
            </Button>
          </Badge>
          <Badge
            color="#F56C6C"
            count={data.filter((item) => item.layout == 1).length}
            overflowCount={999}
          >
            <Button onClick={() => screening(data.filter((item) => item.layout === 1))}>
              长期派遣
            </Button>
          </Badge>
          <Badge
            color="#F56C6C"
            count={data.filter((item) => item.layout == 2).length}
            overflowCount={999}
          >
            <Button onClick={() => screening(data.filter((item) => item.layout === 2))}>
              短期派遣
            </Button>
          </Badge>
          <Badge
            color="#F56C6C"
            count={data.filter((item) => item.layout == 3).length}
            overflowCount={999}
          >
            <Button onClick={() => screening(data.filter((item) => item.layout === 3))}>
              学员
            </Button>
          </Badge>
          <Badge color="#F56C6C" count={repeat.length} overflowCount={999}>
            <Button onClick={() => screening(repeat)}>重复人员</Button>
          </Badge>
          <Button onClick={() => screening(data)}>重置</Button>
        </div>
        <div className={styles.top_feature_box}>
          <Button
            style={{ backgroundColor: '#F56C6C', color: 'white' }}
            color="red"
            variant="solid"
            onClick={showdelete}
          >
            批量删除
          </Button>
          <Button
            style={{ backgroundColor: '#67C23A', color: 'white' }}
            color="red"
            variant="solid"
          >
            导出员工
          </Button>
          <Button
            style={{ backgroundColor: '#409EFF', color: 'white' }}
            color="red"
            variant="solid"
          >
            导入员工
          </Button>
        </div>
      </div>
      {/* 搜索输入框整体 */}
      <div className={styles.top_search_box}>
        <div className={styles.searchInput_box}>
          <Form form={form} layout="inline">
            {/* 员工姓名 */}
            <Form.Item<FieldType> className={styles.formItem} name="name">
              <Input
                placeholder="请输入员工姓名"
                className={styles.searchInput}
                prefix={<SearchOutlined />}
              />
            </Form.Item>
            {/* 公司选择 */}
            <Form.Item<FieldType> className={styles.formItem} name="company">
              <Select
                onChange={searchData}
                style={{ width: 150 }}
                options={company.map((item) => ({
                  value: item.account,
                  label: item.account,
                }))}
                placeholder="请选择公司"
                allowClear
              />
            </Form.Item>
            {/* 项目名称 */}
            <Form.Item<FieldType> className={styles.formItem} name="itemName">
              <Input
                onInput={searchData}
                className={styles.searchInput}
                placeholder="请输入项目名称"
                prefix={<SearchOutlined />}
              />
            </Form.Item>
            {/* 档级选择 */}
            <Form.Item<FieldType> className={styles.formItem} name="grade">
              <TreeSelect
                onChange={searchData}
                treeData={graed}
                placeholder="请选择档级"
                allowClear
                treeDefaultExpandAll
                showSearch
                style={{ width: 150 }}
              />
            </Form.Item>
            {/* 证书选择 */}
            <Form.Item<FieldType> className={styles.formItem} name="cert">
              <Select
                onChange={searchData}
                style={{ width: 150 }}
                options={cert.map((item) => ({
                  value: item.id,
                  label: item.title,
                }))}
                placeholder="请选择证书"
                allowClear
              />
            </Form.Item>

            {/* 月份选择 */}
            <Form.Item<FieldType> style={{ margin: 0 }} name="month">
              <DatePicker onChange={searchData} picker="month" />
            </Form.Item>
          </Form>
        </div>
        <Button
          style={{ backgroundColor: '#0052CC', color: 'white' }}
          color="red"
          variant="solid"
          onClick={showModal}
        >
          新增
        </Button>
      </div>
      {/* 分页的渲染 */}
      <Table<DataTransfer>
        style={{ marginTop: '30px' }}
        bordered={true}
        className={styles.customTable}
        pagination={false}
        columns={columns}
        rowKey={(record) => record.id}
        rowSelection={{ type: selectionType, ...rowSelection }}
        dataSource={paginatedData}
        scroll={{ x: 'max-content' }}
      />
      <Pagination
        style={{ margin: '30px 0px' }}
        align="center"
        current={currentPage}
        pageSize={pageSize}
        total={pageData.length}
        showQuickJumper
        showSizeChanger
        showTotal={(total) => `共 ${total} 条数据`}
        onChange={handlePageChange}
        onShowSizeChange={(current, size) => handlePageChange(1, size)}
      />
      {/* 添加弹窗 */}
      <Modal
        title="添加人员信息"
        open={open}
        onOk={affirm}
        onCancel={hideModal}
        okText="确认"
        cancelText="取消"
        width={900}
        style={{ top: 20 }}
      >
        <Form form={append} className={styles.addFormStyle}>
          <Form.Item<AppendForm>
            name="name"
            layout="vertical"
            label="姓名"
            rules={AddRules.name}
            className={styles.addItem}
          >
            <Input placeholder="请输入员工姓名" disabled={EditOpen} />
          </Form.Item>
          <Form.Item<AppendForm>
            name="tel"
            layout="vertical"
            label="手机号"
            rules={AddRules.tel}
            className={styles.addItem}
          >
            <Input placeholder="请输入手机号" disabled={EditOpen} />
          </Form.Item>
          <Form.Item<AppendForm>
            name="idcard"
            layout="vertical"
            label="证件号"
            rules={AddRules.idcard}
            className={styles.addItem}
          >
            <Input placeholder="请输入证件号" onInput={birthdayRender} />
          </Form.Item>
          <Form.Item<AppendForm>
            name="sex"
            layout="vertical"
            label="性别"
            className={styles.addItem}
          >
            <Select
              disabled={true}
              options={[
                { value: '男', label: '男' },
                { value: '女', label: '女' },
              ]}
              placeholder="输入身份证号自动填充"
              allowClear
            />
          </Form.Item>
          <Form.Item<AppendForm>
            name="birthday"
            layout="vertical"
            label="生日"
            className={styles.addItem}
          >
            <Input disabled={true} placeholder="输入证件号自动填充" />
          </Form.Item>
          <Form.Item<AppendForm>
            name="address"
            layout="vertical"
            label="籍贯"
            rules={AddRules.address}
            className={styles.addItem}
          >
            <Input placeholder="请输入籍贯" />
          </Form.Item>
          <Form.Item<AppendForm>
            name="gradeid"
            layout="vertical"
            label="岗位档级"
            rules={AddRules.gradeid}
            className={styles.addItem}
          >
            <TreeSelect
              disabled={EditOpen}
              className={styles.monthSelect}
              treeData={graed}
              placeholder="请选择档级"
              allowClear
              treeDefaultExpandAll
              showSearch
              onChange={laborage}
            />
          </Form.Item>
          <Form.Item<AppendForm>
            name="base_pay"
            layout="vertical"
            label="岗位工资"
            className={styles.addItem}
          >
            <Input placeholder="选择档级后自动填充" disabled={true} />
          </Form.Item>
          <Form.Item<AppendForm>
            name="record"
            layout="vertical"
            label="学历"
            rules={AddRules.record}
            className={styles.addItem}
          >
            <Select
              options={[
                { label: '初中及以下', value: '初中及以下' },
                { label: '高中/中专', value: '高中/中专' },
                { label: '大专', value: '大专' },
                { label: '本科', value: '本科' },
                { label: '研究生', value: '研究生' },
                { label: '博士', value: '博士' },
              ]}
              placeholder="请选择学历"
              allowClear
            />
          </Form.Item>
          <Form.Item<AppendForm>
            name="bank"
            layout="vertical"
            label="开户行"
            rules={AddRules.bank}
            className={styles.addItem}
          >
            <Input placeholder="请输入开户行" />
          </Form.Item>
          <Form.Item<AppendForm>
            name="bank_card"
            layout="vertical"
            label="银行卡号"
            rules={AddRules.bank_card}
            className={styles.addItem}
          >
            <Input placeholder="请输入银行卡号" />
          </Form.Item>
          <Form.Item<AppendForm>
            name="political_status"
            layout="vertical"
            label="政治面貌"
            rules={AddRules.political_status}
            className={styles.addItem}
          >
            <Select
              options={[
                { label: '党员', value: '党员' },
                { label: '群众', value: '群众' },
                { label: '团员', value: '团员' },
              ]}
              placeholder="请选择政治面貌"
              allowClear
            />
          </Form.Item>
          <Form.Item<AppendForm>
            name="companyid"
            layout="vertical"
            label="公司"
            rules={AddRules.companyid}
            className={styles.addItem}
          >
            <Select
              disabled={EditOpen}
              options={company.map((item) => ({
                value: item.id,
                label: item.account,
              }))}
              placeholder="请选择公司"
              allowClear
              onChange={projectRender}
            />
          </Form.Item>
          <Form.Item<AppendForm>
            name="projectid"
            layout="vertical"
            label="项目"
            rules={AddRules.projectid}
            className={styles.addItem}
          >
            <Select
              disabled={EditOpen}
              options={project.map((item) => ({
                value: item.id,
                label: item.title,
              }))}
              placeholder="请选择项目"
              allowClear
            />
          </Form.Item>
          <Form.Item<AppendForm>
            name="layout"
            layout="vertical"
            label="用工形式"
            rules={AddRules.layout}
            className={styles.addItem}
          >
            <Select
              options={[
                { value: 1, label: '长期派遣' },
                { value: 2, label: '短期派遣' },
                { value: 3, label: '学员' },
              ]}
              placeholder="请选择用工形式"
              allowClear
            />
          </Form.Item>
          <Form.Item<AppendForm>
            name="status"
            layout="vertical"
            label="员工状态"
            rules={AddRules.status}
            className={styles.addItem}
          >
            <Select
              options={[
                { value: 1, label: '在岗' },
                { value: 2, label: '离职' },
              ]}
              placeholder="请选择员工状态"
              allowClear
            />
          </Form.Item>
          <Form.Item<AppendForm>
            name="agreement_end"
            layout="vertical"
            label="合同到期时间"
            rules={AddRules.agreement_end}
            className={styles.addItem}
          >
            <DatePicker format="YYYY-MM-DD" className={styles.monthSelect} />
          </Form.Item>
          <Form.Item<AppendForm>
            name="agreement_num"
            layout="vertical"
            label="现合同期限（年）"
            rules={AddRules.agreement_num}
            className={styles.addItem}
          >
            <Input placeholder="请输入合同期限" />
          </Form.Item>
          {EditOpen && (
            <>
              <Form.Item
                name="gr_security"
                layout="vertical"
                label="个人社保基数"
                className={styles.addItem}
              >
                <Input placeholder="请输入个人社保基数" />
              </Form.Item>
              <Form.Item
                name="dw_security"
                layout="vertical"
                label="单位社保基数"
                className={styles.addItem}
              >
                <Input placeholder="请输入单位社保基数" />
              </Form.Item>
            </>
          )}
          <Form.Item<AppendForm>
            name="entry_time"
            layout="vertical"
            label="入职时间"
            rules={AddRules.entry_time}
            className={styles.addItem}
          >
            <DatePicker format="YYYY-MM-DD" className={styles.monthSelect} />
          </Form.Item>
          <Form.Item<AppendForm>
            name="leave_time"
            layout="vertical"
            label="离职时间"
            className={styles.addItem}
          >
            <DatePicker defaultValue="" format="YYYY-MM-DD" className={styles.monthSelect} />
          </Form.Item>
        </Form>
      </Modal>
      {/* 抽屉 */}
      <Drawer
        title="员工信息"
        closable={{ 'aria-label': 'Close Button' }}
        onClose={onClose}
        open={DrawerState}
        width={900}
        classNames={{
          header: 'my-classname',
        }}
      >
        <Tabs defaultActiveKey="1" items={items} />
      </Drawer>

      <Modal
        title="删除"
        open={deleteOpen}
        onOk={deleteData}
        centered
        onCancel={hidedelete}
        okText="确认"
        cancelText="取消"
      >
        <div className={styles.deleteBox}>
          <img className={styles.delete} src={require('../img/warn.png')} alt="" />
          确定要删除这些员工吗?
        </div>
      </Modal>
    </div>
  );
}
